import useClipboard from 'vue-clipboard3'

const { toClipboard } = useClipboard()

/**
 * 复制文本到剪贴板
 * @param text 文本
 */
export const copyText = async (text: string) => {
  return toClipboard(text)
}

export const formatDate = (date: Date | string) => {
  let tempDate: Date
  if (typeof date === 'string') {
    tempDate = new Date(date)
  } else {
    tempDate = date
  }
  return tempDate.toLocaleTimeString()
}

/**
 * 函数防抖
 *
 * @param func 函数
 * @param delay 防抖间隔
 * @param immediate
 */
export const debounce = <F extends (...args: any[]) => any>(
  func: F,
  delay: number,
  immediate?: boolean
) => {
  let timer: ReturnType<typeof setTimeout> | null = null
  return function (this: ThisParameterType<F>, ...args: Parameters<F>) {
    const context = this
    if (timer) {
      clearTimeout(timer)
    }
    if (immediate) {
      const firstRun = !timer
      timer = setTimeout(() => {
        timer = null
      }, delay)
      if (firstRun) {
        func.apply(context, args)
      }
    } else {
      timer = setTimeout(() => {
        func.apply(context, args)
      }, delay)
    }
  }
}
